<?php
namespace backend\modules\mbapi\models;

use common\models\User as BaseUser;
use Yii;

class User extends BaseUser
{
    /**
     * 生成 access_token
     */
    public function generateApiToken()
    {
        $this->access_token = Yii::$app->security->generateRandomString() . '_' . time();
    }

    /**
     * 校验access_token是否有效
     */
    public static function apiTokenIsValid($token)
    {
        if (empty($token)) {
            return false;
        }

        $timestamp = (int) substr($token, strrpos($token, '_') + 1);
        $expire = 1*24*3600; // Yii::$app->params['user.apiTokenExpire'];
        return $timestamp + $expire >= time();
    }

    public static function findIdentityByAccessToken($token, $type = null)
    {
        // 如果token无效的话，
        if($token && !static::apiTokenIsValid($token)) {
            throw new \yii\web\UnauthorizedHttpException("token 无效或过期");
        }

        return static::findOne(['access_token' => $token, 'status' => self::STATUS_ACTIVE]);
        // throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
    }
}